{% extends "userpage.html" %}

{% block title %}Your Product Order - {{super()}}{% endblock %}

{% block extrahdrs %}
{% endblock %}


{% block sidemenu %}
	{#
	TODO: provide summary of ordered items somewhere
	
	TODO: my google chrome still has a problem updating total correctly on later rows..
	
	#}
	<br /><br />
	<div style="position:fixed" class="notice" style="margin-left:-40px;">
		Order Total: <span id="total-cost">--</span>
	</div>
	<noscript><br /><br /><br /><div class="error" style="margin-left:-30px;">Enable javascript to see total!</div></noscript>
{% endblock %}


{% block body %}

# if saved
	<div class="disappear success plus1" style="position:absolute;top:15px;right:15px;width:220px;text-align:center;">Your order has been saved.</div>
# endif

{% import '_product_list.html' as plist %}
<form action="/" method="post" id="pl-form">
<h3>Your Product Order &nbsp; &nbsp; &nbsp; <button name="action" value="order" type="submit" class="order-submit" style="font-size:0.8em;">&nbsp; Save &nbsp;</button></h3> 
	
# if current_list
	# if error
		<div class="disappear plus1 error">{{error}}</div>
	# endif

	<div class="plus1" style="margin-bottom:15px;">
		Based on product availability as of {{ localtime(current_list.created).strftime('%B') }} {{ localtime(current_list.created).strftime('%d').strip('0') }}.
	</div>

	<p class="plus1">
		# if current_list.notes
			{{current_list.render_notes()|safe}}
		# else
			{# <em>(no notes)</em> #}
		# endif
	</p>
	
	{{ plist.product_list_table(buyer_list, editable=True) }}
	<script type="text/javascript">
		function number_format(number, decimals, dec_point, thousands_sep) {
		    var n = !isFinite(+number) ? 0 : +number, 
		        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
		        s = '',
		        toFixedFix = function (n, prec) {
		            var k = Math.pow(10, prec);
		            return '' + Math.round(n * k) / k;        };
		    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
		    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
		    if (s[0].length > 3) {
		        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
		    if ((s[1] || '').length < prec) {
		        s[1] = s[1] || '';
		        s[1] += new Array(prec - s[1].length + 1).join('0');
		    }    return s.join(dec);
		}
		// TODO: fix google chrome issue!!
		var total = 0.0;
		function update_total() {
			var new_total = 0;
			var rows = $('.row-amount');
			for (var i = 0; i < rows.length; ++i) {
				var amount = $(rows[i]).val();
				// prevent negative numbers, accept 0.0, .5, 6.5, etc
				if (amount.match(/^\d+(\.\d+)?$/) || amount.match(/^\.\d+$/)) {
					amount *= 1.0;
					var unit_price = $.trim($('#'+$(rows[i])[0].id.replace('-amount','-price')).html()) * 1.0;
					var cost = amount * unit_price;
					//$(rows[i]).data('cost', cost);
					new_total += cost;
					$(rows[i]).css('color','');
				} else if (amount) {
					//$(rows[i]).data('cost', 0);
					// highlight in red
					$(rows[i]).css('color','red');
				} else {
					//$(rows[i]).data('cost', 0);
				}
			}
			total = new_total;
			$('#total-cost').text('$'+number_format(new_total, 2));
		}
		/* // crazy caching single row updating version, requires uncommenting data(..) calls above
		function update_total_one(el) {
			var _this = el;
			var new_total = total;
			var old_cost = $(_this).data('cost');
			if (!old_cost) old_cost = 0;
			var amount = $(_this).val();
			// prevent negative numbers, accept 0.0, .5, 6.5, etc
			if (amount.match(/^\d+(\.\d+)?$/) || amount.match(/^\.\d+$/)) {
				amount *= 1.0;
				var unit_price = $.trim($('#'+$(_this)[0].id.replace('-amount','-price')).html()) * 1.0;
				var cost = amount * unit_price;
				new_total += cost - old_cost;
				$(_this).data('cost', cost);
				$(_this).css('color','');
			} else if (amount) {
				$(_this).data('cost', 0);
				new_total -= old_cost;
				// highlight in red
				$(_this).css('color','red');
			} else {
				$(_this).data('cost', 0);
				new_total -= old_cost;
			}
			total = new_total;
			var nftotal = '$'+number_format(new_total, 2);
			//$('#total-cost').html(nftotal); // google chrome doesn't like this..
			//$('#total-cost')[0].innerHTML = nftotal; // or this..
			$('#total-cost').text(nftotal);
		}
		$('.row-amount').live('keyup', function() { update_total_one(this); });
		*/
		$('.row-amount').keyup(update_total);
		update_total();
		
		setTimeout(function() {
			$('.disappear.success').fadeOut();	
		}, 2800);
		setTimeout(function() {
			$('.disappear.error').fadeOut();	
		}, 30 * 1000);
		
		
	</script>
	<label for="notes">Notes to Seller</label> <br/>
	<textarea id="notes" name="notes" class="notes">{{buyer_list.notes}}</textarea><br/>
# else
	<br /><br />
	<p class="plus1 notice" style="width:350px;">
		No product list available yet!<br />
		We'll let you know when the new one is released.
	</p> 
# endif

<input type="hidden" name="source_list_key" value="{{current_list.key()}}" />
<button name="action" value="order" type="submit" class="order-btn order-submit">&nbsp; Save &nbsp;</button>
</form>
{% endblock %}
